﻿using ComponentFactory.Krypton.Toolkit;
using System;
using System.Data.Common;
using System.Linq;
using System.Windows.Forms;
using Telerik.OpenAccess.Data.Common;
using TfsHelper.Model;

namespace TfsHelper.WinFrontEnd
{
    public partial class frmDetails : KryptonForm
    {
        #region " Fields "

        private int workitemId = 0;

        private BindingSource source = new BindingSource();
        private long totalTicks = 0;

        #endregion

        #region " Constructor "

        public frmDetails()
        {
            InitializeComponent();
        }

        #endregion

        #region " Properties "

        public bool ChangedData { get; set; }

        #endregion

        #region " Handlers "

        private void gridTimes_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow row in gridTimes.Rows)
            {
                if (row.Cells[4].Value != null)
                {
                    var time = (DateTime)row.Cells[4].Value - (DateTime)row.Cells[3].Value;
                    totalTicks += time.Ticks;
                    row.Cells[5].Value = time.ToString("hh\\:mm");

                    int minutes = time.Minutes;
                    double round = (double)minutes / 60 * 100;
                    minutes = Convert.ToInt32(Math.Round(round / 25, MidpointRounding.ToEven) * 25);

                    if (minutes == 100)
                        row.Cells[6].Value = (time.Hours + 1).ToString().PadLeft(2, '0') + ".00";
                    else
                        row.Cells[6].Value = time.Hours.ToString().PadLeft(2, '0') + "." + minutes.ToString().PadLeft(2, '0');
                }
            }
            gridTimes.Columns[0].Visible = false;

            lblTotalTime.Text = "TOTAL: " + new TimeSpan(totalTicks).ToString("hh\\:mm");
            totalTicks = 0;
        }

        private void btnFilter_Click(object sender, EventArgs e)
        {
            gridTimes.DataSource = null;
            LoadGrid(workitemId);
        }

        #endregion

        #region " Methods "

        public void ShowDetail(int workitemId, string title)
        {
            lblTitle.Text = title;
            dtpFrom.Value = DateTime.Today;
            dtpTo.Value = DateTime.Today;
            this.workitemId = workitemId;
            ChangedData = false;

            LoadGrid(workitemId);

            ShowDialog();
        }

        private void LoadGrid(int workitemId)
        {
            using (TfsModel model = new TfsModel())
            {
                var colTimes = model.Time
                    .Where(x => x.WorkitemId == workitemId)
                    .Where(x => x.Start >= dtpFrom.Value && x.Start <= dtpTo.Value.AddDays(1).AddSeconds(-1));

                source.DataSource = colTimes;
                gridTimes.DataSource = source;
            }
        }

        #endregion

        private void frmDetails_Load(object sender, EventArgs e)
        {

        }

        private void gridTimes_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            btnSaveChanges.Enabled = true;
        }

        private void btnSaveChanges_Click(object sender, EventArgs e)
        {
            using (TfsModel model = new TfsModel())
            {
                try
                {
                    foreach (DataGridViewRow row in gridTimes.Rows)
                    {
                        model.ExecuteNonQuery(
                            "UPDATE Times SET Start = @start, Finish = @finish WHERE TimeId = @id",
                            new OAParameter("@start", Convert.ToDateTime(row.Cells[3].Value)),
                            new OAParameter("@finish", Convert.ToDateTime(row.Cells[4].Value)),
                            new OAParameter("@id", Convert.ToInt32(row.Cells[0].Value))
                            );
                    }

                    model.SaveChanges();
                }
                catch (Exception exc)
                {
                    KryptonMessageBox.Show("There was an error trying to update the information.\n" + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            KryptonMessageBox.Show("The information was saved correctly", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
            btnSaveChanges.Enabled = false;
            ChangedData = true;
        }
    }
}
